package middleware

import (
	"RocFamilySystem/models"
	"RocFamilySystem/pkg/constant"
	"RocFamilySystem/tools/container"
	"RocFamilySystem/tools/jwt"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis/v8"
	"log"
	"net/http"
	"strings"
	"time"
)

// Authority 验证用户是否登录
func Authority() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		token := ctx.GetHeader("token")

		//没有登录
		if strings.TrimSpace(token) == "" {
			ctx.Next()
			return
		}

		//有token
		sub := jwt.ParseToken(token)
		client := container.GetBeanFromContainer("redis.Client").(*redis.Client)
		val := client.HGet(ctx, constant.REDIS_KEY_SYS_LOGINUSERID_TOKEN+sub, token).Val()
		if val == "" {
			log.Panicln(constant.AUTHORITY_ERROR)
			ctx.Abort()
		}

		//获取用户的信息
		userInfoJson := client.Get(ctx, fmt.Sprintf("%s:%s", constant.REDIS_KEY_SYS_LOGINUSER, sub)).Val()

		//用户信息不存在需要重新登录
		if userInfoJson == "" {
			ctx.JSON(http.StatusOK, gin.H{
				"code": 401,
				"msg":  "登录过期",
			})
			ctx.Abort()
			return
		}
		var sysUser models.SysUser
		json.Unmarshal([]byte(userInfoJson), &sysUser)
		//更新用户信息存储时间
		client.Expire(ctx, fmt.Sprintf("%s:%d", constant.REDIS_KEY_SYS_LOGINUSER, *sysUser.Id), time.Hour*24*7)
		ctx.Set(constant.REQUEST_CONTEXT_LOGIN_USER_ID, sub)
		ctx.Set(constant.REQUEST_CONTEXT_LOGIN_USERINFO, sysUser)
		ctx.Next()
	}
}
